# encoding=utf-8
import os
import logging
from logging.handlers import TimedRotatingFileHandler
import yaml


class AppConfig:
    # 常规配置
    PROJECT_PATH = os.path.join(os.path.dirname(__file__))
    RESOURCES_PATH = os.path.join(PROJECT_PATH, "AppConfig.yaml")
    CACHE_PATH = os.path.join(PROJECT_PATH, "runtime-cache")
    LOGGER_PATH = os.path.join(PROJECT_PATH, "runtime-log")


os.makedirs(AppConfig.CACHE_PATH, exist_ok=True)
os.makedirs(AppConfig.LOGGER_PATH, exist_ok=True)


with open(AppConfig.RESOURCES_PATH, "r") as f:
    _y = yaml.safe_load(f)
    CAP_AUTO_FOCUS = _y["CAP_AUTO_FOCUS"]
    CAP_INDEX = _y["CAP_INDEX"]
    CAP_WIDTH = _y["CAP_WIDTH"]
    CAP_HEIGHT = _y["CAP_HEIGHT"]
    CAP_FPS = _y["CAP_FPS"]
    CAP_TIME = _y["CAP_TIME"]
    WIN_WIDTH = _y["WIN_WIDTH"]
    WIN_HEIGHT = _y["WIN_HEIGHT"]
    assert CAP_INDEX != ""
    assert CAP_WIDTH != ""
    assert CAP_HEIGHT != ""
    assert CAP_FPS != ""
    assert CAP_TIME != ""
    assert WIN_WIDTH != ""
    assert WIN_HEIGHT != ""


# 日志配置
def set_logger():
    logger = logging.getLogger()  # root
    logger.setLevel(logging.INFO)

    file_handler = TimedRotatingFileHandler(
        filename=os.path.join(AppConfig.LOGGER_PATH, "app-log"),
        when='D', interval=1
    )
    file_handler.suffix = "%Y-%m-%d.log"

    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)

    logging_format = logging.Formatter(
        "%(asctime)s - %(filename)s - %(funcName)s - %(lineno)d - %(levelname)s - %(message)s")

    file_handler.setFormatter(logging_format)
    console_handler.setFormatter(logging_format)

    logger.addHandler(file_handler)
    logger.addHandler(console_handler)


set_logger()
